package org.wlw.web.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.wlw.web.mapper.UserMapper;
import org.wlw.web.models.Pager;
import org.wlw.web.models.User;
import org.wlw.web.models.WebException;
import org.wlw.web.service.IUserService;

import java.util.List;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;

    private User loadByUsername(String username) {
        return userMapper.loadByUsername(username);
    }

    @Override
    public void add(User user) {
        if (user.getPassword() == null || user.getPassword().length() < 6) {
            throw new WebException("用户名或者密码不合理！");
        }
        if (loadByUsername(user.getUsername()) != null) {
            throw new WebException("添加的用户已经存在了!");
        }
        userMapper.add(user);
    }

    @Override
    public void update(User user) {
        if (user.getPassword() == null || user.getPassword().length() < 6) {
            throw new WebException("用户名或者密码不合理！");
        }
        userMapper.update(user);
    }

    @Override
    public void delete(int id) {
        int a = 10;
        if (a == 10) {
            throw new RuntimeException("测试异常信息");
        }
        userMapper.delete(id);
    }

    @Override
    public User load(int id) {
        return userMapper.load(id);
    }

    @Override
    public List<User> list(User user) {
        return userMapper.list(user);
    }

    @Override
    public Pager<User> find(User t) {
        //第一段aop
        List<User> datas = userMapper.find(t);
        int total = userMapper.findByCount(t);
        Pager<User> pager = new Pager<>();
        pager.setData(datas);
        pager.setTotals(total);
        return pager;
    }
}
